﻿using Avalon.Core.Data;
using Avalon.Core.MVC.Attributes;
using Avalon.Core.MVC.StateBags;
using System;

namespace Avalon.Core.MVC.Actions
{
    [PipelineAction("SaveEntityAction")]
    public sealed class SaveEntityAction<TModel> : IPipelineAction where TModel : class, IEntity, new()
    {
        public int Index { get; set; }
        public void Execute(IStateBag stateBag)
        {
            try {
                IRepository<TModel> repostitory = RepositoryConfig.Initialize<TModel>();
                if (stateBag.ParameterValues.ContainsKey("Model")) {
                    TModel model = (TModel)stateBag.ParameterValues["Model"];
                    if (model.Id == Guid.Empty) {
                        repostitory.Add(model);
                    }
                    else {
                        repostitory.Update(model);
                    }
                }
                repostitory.SaveChanges();
            }
            catch (Exception ex) {
                stateBag.Error = new Exception(string.Format("failed to save entity: {0}", typeof(TModel).Name), ex);
            }
        }
    }
}